﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;
using Verse.AI;

namespace Miao.Stand
{
    /// <summary>
    /// 工作驱动器，默认替身将一直跟随在玩家附近
    /// </summary>
    public class JobDriver_StandFollowMaster : JobDriver_StandBase
    {

    

        //public override bool TryMakePreToilReservations(bool errorOnFailed)
        //{
        //    return pawn.Reserve(base.TargetLocA, job, 1, -1, null, errorOnFailed);
        //}
      
        /// <summary>
        //这是个抽象函数,我们的jobDriver要实现它, 在这个函数中我们要声明保留某个目标, 不让其他物体与之交互。比如小人正在屠宰一个生物，读条中，如果没有声明保留那个生物，这个时候可能另一个小人也走过来一起屠宰，当然RW里并没有协同工作一说，只是发生这种情况不符合RW开发者的预期，可能会出错。
        //一旦声明为false，则可终结当前的操作。
        /// </summary>
        /// <param name="errorOnFailed"></param>
        /// <returns></returns>
        public override bool TryMakePreToilReservations(bool errorOnFailed)
        {
            return true;
            //throw new NotImplementedException();
        }
        protected IntRange ticksBetweenWandersRange = new IntRange(20, 100);//超时时间
        protected override IEnumerable<Toil> MakeNewToils()
        {
            //Messages.Message("替身已开始执行跟随工作", MessageTypeDefOf.NeutralEvent);
            this.FailOnDespawnedOrNull(TargetIndex.A);
            Toil toil = new Toil();
            //toil.tickAction = TickAction;
            toil.tickAction = delegate
            {
                Pawn target = standPawn.owner;
                //Pawn target = (Pawn)job.GetTarget(TargetIndex.A).Thing;//获得执行游荡命令的A目标
                if (!base.pawn.Position.InHorDistOf(target.Position, standPawn.WanderRanage)) //当处于漫游外触发
                {
                    Follower(target);
                }
                else if (!base.pawn.pather.Moving)//在4格内
                {
                    Surround(target);
                }

            };
            toil.defaultCompleteMode = ToilCompleteMode.Never;
            yield return toil;

        }

        private void Follower(Pawn target)
        {
            if (!base.pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly))
            {
                EndJobWith(JobCondition.Incompletable);
            }
            else if (!base.pawn.pather.Moving || base.pawn.pather.Destination != target)//如果没有处于移动或者移动点不等于自身
            {
                //Messages.Message("寻路开始", MessageTypeDefOf.NeutralEvent);
                base.pawn.pather.StartPath(target, PathEndMode.Touch);//进行寻路
            }
        }
        protected LocomotionUrgency locomotionUrgency = LocomotionUrgency.Walk;//行动模式
        protected Danger maxDanger = Danger.None;//威胁
        //bool lockStop;
        private void Surround(Pawn target)
        {
            //Messages.Message("环绕开始", MessageTypeDefOf.NeutralEvent);
           
            #region 计算游荡点
            IntVec3 exactWanderDest = GetExactWanderDest(standPawn, standPawn.WanderRanage);//精确漫游目的地
                                                                                      //job.expiryInterval = ticksBetweenWandersRange.RandomInRange;//有效期

            #endregion
            #region 执行游荡

            if (pawn.mindState.nextMoveOrderIsWait)
            {
                job.expiryInterval = ticksBetweenWandersRange.RandomInRange;
                base.pawn.pather.StartPath(exactWanderDest, PathEndMode.Touch);//进行寻路游荡
                
            }
            else
            {
                if(Find.TickManager.TicksGame % 1000 ==0)
                {
                    pawn.mindState.nextMoveOrderIsWait = false;
                }
                else
                {
                    pawn.mindState.nextMoveOrderIsWait = true;
                }
                //job.expiryInterval = ticksBetweenWandersRange.RandomInRange;
                pawn.pather.StopDead();
            }

            //pawn.mindState.nextMoveOrderIsWait = !pawn.mindState.nextMoveOrderIsWait;


            #endregion
            #region 游荡一会后待机

            #endregion
            //Toils_Goto.GotoCell(exactWanderDest, PathEndMode.OnCell);
            //IntVec3 intVec3 =  WanderUtility.GetColonyWanderRoot(pawn);//找到游荡根
            //IntVec3 exactWanderDest = GetExactWanderDest(pawn);//精确漫游目的地


        }
        /// <summary>
        /// 获得准确的漫游目的地
        /// </summary>
        /// <param name="pawn"></param>
        /// <returns></returns>
        protected virtual IntVec3 GetExactWanderDest(Pawn pawn,float wanderRadius)
        {
            IntVec3 wanderRoot = GetWanderRoot(pawn);
            float radius = wanderRadius;
            PawnDuty duty = pawn.mindState.duty;
            if (duty != null && duty.wanderRadius.HasValue)
            {
                radius = duty.wanderRadius.Value;
            }
            //随机游荡目的地
            return RCellFinder.RandomWanderDestFor(pawn, wanderRoot, radius, wanderDestValidator, PawnUtility.ResolveMaxDanger(pawn, maxDanger));
        }
        bool wanderDestValidator(Pawn pawn, IntVec3 loc, IntVec3 root)
        {
            return true;
        }


        protected virtual IntVec3 GetWanderRoot(Pawn pawn)
        {
            return pawn.Position;
        }
    }
}
